// components/leaflet/leaflet.js
import {getScenicArea, getScenicAreaDetail, getRoadDetail} from "./request.js";
import {closePoiPopup} from './zhgeo.dom'
import {DefaultIcons} from "../../config"
import {getServeUrl} from '../../index'
import MinaTouch from './utils/mina-touch';
import {wgs84ToGcj02} from './LagLng.Utils'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    rootScenicId: String
  },

  /**
   * 组件的初始数据
   */
  data: {
      mapTop: 0,
      mapLeft: 0,
    //   mapWidth: 320, 
    //   mapHeight: 320, 
      markerBorderColor: '#C1FFE4',
      mapHeight: wx.getSystemInfoSync().windowHeight,
      mapWidth: wx.getSystemInfoSync().windowWidth,
      overlayCanvasTop: 0,
      overlayCanvasLeft: 0,
      overlayCanvasHeight: 0,//wx.getSystemInfoSync().windowHeight,
      overlayCanvasWidth: 0,//wx.getSystemInfoSync().windowWidth,
      markers: {},
      popups: {},
      zoomLevelList:{},
      mapPane: {
          top: 0,
          left: 0,
          setPosition: 'setMapPanePosition',
          getPosition: 'getMapPanePosition'
      },
      controlCorners: {
          topleft: [],
          topright: [],
          bottomleft: [],
          bottomright: []
      },
      controlZoom: {
        zoomIn: {
            disabled: false,
            addEventListener: function(event, func, useCapture) {
                global.wxDOM.addEventListener(this, event, func, useCapture);
            },
            removeEventListener: function(event, func, useCapture) { 
                global.wxDOM.removeEventListener(this, event, func, useCapture);
            }
        },
        zoomOut: {
            disabled: false,
            addEventListener: function(event, func, useCapture) {
                global.wxDOM.addEventListener(this, event, func, useCapture);
            },
            removeEventListener: function(event, func, useCapture) { 
                global.wxDOM.removeEventListener(this, event, func, useCapture);
            }
        },
      },
      /// poi half screen
      poiHalfScreenShow: false, 
      /// ScenicAreaChildren
      scenicTypeList: [],
      /// poi详情half screen
      isAudioPlay: false,
      poiDetailHalfScreenShow: false,
      poiOfPoiDetail: null,
      audioRemainingTime: "00:00",
      loadingAudio: true,
      defaultIcons: new DefaultIcons(),
      roadMultiArray: [[],[]],
      roadMultiIndex: [0, 0],
      showRoadControl: false,
      compassRotateAngle: 0,
      multimap: [],
      baseUrl: getServeUrl(),
      scenicShowControl: false,
      scenicShowHalfScreenShow: false,
      scenicShowList: [],
      targetShowTimeScenic: null,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    processMarkerEvent(event) {
        return global.wxDOM.processMarkerEvent(event);
    },
    processEvent(event) {
        return global.wxDOM.processEvent(event);
    },
    addEventListener: function(event, func, useCapture) {
        global.wxDOM.addEventListener(this, event, func, useCapture);
    },
    removeEventListener: function(event, func, useCapture) { 
        global.wxDOM.removeEventListener(this, event, func, useCapture);
    },
    processZoomInEvent(event) {
        return global.wxDOM.processZoomInEvent(event);
    },
    processZoomOutEvent(event) {
        return global.wxDOM.processZoomOutEvent(event);
    },
    /// poi选择 half screen
    openPoiHalfScreen() {
        this.setData({
            poiHalfScreenShow: true
        })
    },
    /// 显示表演时间
    openScenicShowHalfScreen() {
        let that = this;
        let scenic_list = []    // 所有包含表演时间的景点
        let children_scenic_area_type = that.scenicArea.children_scenic_area_type
        for (let t=0; t<children_scenic_area_type.length; ++t) {
            for (let s=0; s<children_scenic_area_type[t].items.length; ++s) {
                let item = children_scenic_area_type[t].items[s]
                if (item.nearest_show_time != null) {
                    scenic_list.push(item)
                }
            }
        }
        if (scenic_list.length > 0) {
            // 排序
            scenic_list.sort(function(a, b) {
                return a.nearest_show_time.getTime() - b.nearest_show_time.getTime()
            })
        }

        this.setData({
            scenicShowHalfScreenShow: true,
            scenicShowList: scenic_list
        })
    },

    showTargetScenicShowTimeList(evt) {
        let that = this;
        let scenicid = evt.currentTarget.dataset.scenicid
        let children_scenic_area_type = that.scenicArea.children_scenic_area_type
        let scenic = null
        for (let t=0; scenic == null &&t<children_scenic_area_type.length; ++t) {
            for (let s=0; s<children_scenic_area_type[t].items.length; ++s) {                
                let item = children_scenic_area_type[t].items[s]
                if (item.id == scenicid) {
                    scenic = item
                    break;
                }
            }
        }
        if (scenic == null || scenic.today_show_time == null) {
            return
        }

        var recentDate = null
        if (scenic.recent_show_time != null) {
            for (const i in scenic.recent_show_time) {
                if (recentDate == null) {
                    recentDate = scenic.recent_show_time[i]
                } else {
                    if (recentDate.getTime() > scenic.recent_show_time[i].getTime()) {
                        recentDate = scenic.recent_show_time[i]
                    }
                }
            }
        }
        let showTimeList = []
        for (const i in scenic.today_show_time) {
            for (let m=0; m<scenic.today_show_time[i].length; ++m) {
                let ttm = scenic.today_show_time[i][m]
                if (recentDate != null) {
                    if (recentDate.getTime() - 1000 <= ttm.getTime()) {
                        showTimeList.push(ttm)
                    }
                } else {
                    showTimeList.push(ttm)
                }
            }
        }
        showTimeList.sort(function(a, b) {
            return a.getTime() - b.getTime()
        })
        scenic.show_time_str_list = []
        for (let i=0; i<showTimeList.length; ++i) {
            let st = showTimeList[i]
            let ss = st.getMonth() + '月' + st.getDate() + '日'
                + ' ' +  st.getHours() + '时' + st.getMinutes() + '分'
            scenic.show_time_str_list.push(ss)
        }
        that.setData({
            targetShowTimeScenic: scenic
        })
    },

    showAllScenicShowTimeList() {
        var that = this
        that.setData({
            targetShowTimeScenic: null
        })
    },

    _showTypeCheckboxChange(e, typeList) {
        const values = e.detail.value;
        for (let i=0; i<typeList.length; ++i) {
            let show = false;
            for (let j=0; j<values.length; ++j) {
                if (typeList[i].id == values[j]) {
                    show = true;
                    if (!typeList[i].show) {
                        typeList[i].show = true;
                        this.scenicArea.showPois(typeList[i]);
                    }
                    break;
                }
            }
            if (!show) {
                if (typeList[i].show) {
                    typeList[i].show = false;
                    this.scenicArea.hidePois(typeList[i]);
                }
            }
        }
    },

    scenicTypeCheckboxChange(e) {
        this._showTypeCheckboxChange(e, this.data.scenicTypeList);
    },

    showPoiDetailHalfScreen(poi) {
        var that = this;
        if (that.audioContext != null) {
            that.audioContext.stop();
            that.audioContext.destroy();
            that.audioContext = null;
        }
        if (poi.show_audio) {
            that.audioContext = wx.createInnerAudioContext();
            that.audioContext.onCanplay(function() {
                console.log("can play")
                if (that.data.loadingAudio) {
                    // that.audioContext.play();
                    // that.audioContext.pause();
                    // that.audioContext.seek(0);
                }
                // let tm = that.calcAudioTime();
                that.setData({
                    loadingAudio: false,
                    // audioRemainingTime: tm
                })
            })
            that.audioContext.onTimeUpdate(function() {
                let tm = that.calcAudioTime();
                that.setData({
                    audioRemainingTime: tm
                });
            });
            that.audioContext.onEnded(function() {
                that.setData({ isAudioPlay: false });
            })
        }
        if (poi.detailLoaded) {
            if (that.audioContext != null) {
                that.audioContext.src = poi.audio_file;
            }
            that.setData({
                loadingAudio: true,
                isAudioPlay: false,
                poiDetailHalfScreenShow: true,
                poiOfPoiDetail: poi,
                audioRemainingTime: "00:00",
            });
        } else {
            getScenicAreaDetail(poi, function(p) {
                that.showPoiDetailHalfScreen(p);
            });
        }
    },
    closeDetailHalfScreen() {
        var that = this;
        let poi = that.data.poiOfPoiDetail;
        closePoiPopup(poi);
    },
    //播放
    playAudio: function () {
        var that = this;
        if (that.data.loadingAudio) return;
        that.audioContext.play();
        setTimeout(() => {
            let status = that.audioContext.paused;
          }, 100)
        this.setData({ isAudioPlay: true });
    },
    // 停止
    stopAudio: function () {
        var that = this;
        that.audioContext.pause();
        this.setData({ isAudioPlay: false });
    },
    routerNavToChildScenic: function() {
        let that = this;
        if (that.data.poiOfPoiDetail == null) {
            return;
        }
        this.triggerEvent('changeScenic', {
            scenicId: this.data.poiOfPoiDetail.id
        })
    },
    routerNavToMultimap: function(e) {
        var scenicId = e.currentTarget.dataset.scenicid
        this.triggerEvent('redirectScenic', {
            scenicId: scenicId
        })  
    },
    navigateToPoi: function () {
        let that = this;
        if (that.data.poiOfPoiDetail == null || that.data.poiOfPoiDetail.location == null) {
            return;
        }
        const pnt = [that.data.poiOfPoiDetail.location.longitude, that.data.poiOfPoiDetail.location.latitude]; //wgs84ToGcj02(that.data.poiOfPoiDetail.location.longitude, that.data.poiOfPoiDetail.location.latitude)
        const latitude = pnt[1]
        const longitude = pnt[0]
        wx.openLocation({
            latitude,
            longitude,
            scale: that.data.poiOfPoiDetail.zoom
          })

    },
    showLocation: function() {
        let that = global.wx;
        that.scenicArea.showLocation();
    },
    triggerTrail: function() {

    },
    bindRoudMultiPickerChange(e) {
    //   console.log('picker发送选择改变，携带值为', e.detail.value)
      let that = this;
      if (that.scenicArea.roadShowing != null) {
        that.scenicArea.hideRoad(that.scenicArea.roadShowing)
      }
      if (e.detail.value[0] > 0) {
        let iType = e.detail.value[0] - 1;
        let road = that.scenicArea.road_type_list[iType].roads[e.detail.value[1]]
      //   console.log(road)
        if (road.detailLoaded) {
          that.scenicArea.showRoad(road)
        } else {
          getRoadDetail(that.scenicArea, road, function(roadDetail) {
            that.scenicArea.showRoad(roadDetail)
          })
        }          
      }
      this.setData({
        roadMultiIndex: e.detail.value
      })
    },
    bindRoudMultiPickerColumnChange(e) {
      let that = this;
    //   console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
      var data = {
        roadMultiArray: this.data.roadMultiArray,
        roadMultiIndex: this.data.roadMultiIndex
      };
      data.roadMultiIndex[e.detail.column] = e.detail.value;
      switch (e.detail.column) {
        case 0:
          data.roadMultiArray[1] = [];
          if (e.detail.value > 0) {
            let iType = e.detail.value - 1;
            for (let m=0; m<that.scenicArea.road_type_list[iType].roads.length; ++m) {
                data.roadMultiArray[1].push(that.scenicArea.road_type_list[iType].roads[m].name);
            }
            data.roadMultiIndex[1] = 0;
            console.log(data.roadMultiIndex);
          }
          break;
      }
      console.log(data.roadMultiIndex);
      this.setData(data);
    },
    calcAudioTime: function() {
        let that = this
        const thisRemaingTime = Math.round(that.audioContext.duration - that.audioContext.currentTime);
        if (thisRemaingTime != that.audioRemainingTime) {
            that.audioRemainingTime = thisRemaingTime;
            const mm = Math.floor(thisRemaingTime / 60 )
            const ss = Math.round(thisRemaingTime - mm * 60);
            return mm + ':' + ss;
        } else {                
            const mm = Math.floor(that.audioRemainingTime / 60 )
            const ss = Math.round(that.audioRemainingTime - mm * 60);
            return mm + ':' + ss;
        }
    }
  },
  lifetimes: {
    ready: function() {
        console.log('ready')
        var that = this;
        new MinaTouch(this, 'minaTouch', {
            // 2. onload实例化mina-touch
            //会创建this.touch1指向实例对象
            touchStart: function (evt) {
                that.processEvent(evt);
            },
            touchMove: function (evt) {                
                that.processEvent(evt);
            },
            touchEnd: function (evt) {
                that.processEvent(evt);
            },
            touchCancel: function () {},
            multipointStart: function () {
                // console.log('multipointStart');
            }, //一个手指以上触摸屏幕触发
            multipointEnd: function () {
                // console.log('multipointEnd');
            }, //当手指离开，屏幕只剩一个手指或零个手指触发(一开始只有一根手指也会触发)
            tap: function (evt) {
                // that.processEvent(evt);
            }, //点按触发，覆盖下方3个点击事件，doubleTap时触发2次
            doubleTap: function (evt) {
                that.processEvent(evt);
                // console.log('doubleTap');
            }, //双击屏幕触发
            longTap: function () {
                // console.log('longTap');
            }, //长按屏幕750ms触发
            singleTap: function () {
                // console.log('singleTap');
            }, //单击屏幕触发，包括长按
            rotate: function (evt) {
                //evt.angle代表两个手指旋转的角度
                // console.log('rotate:' + evt.angle);
            },
            pinch: function (evt) {
                if (evt.status == 'stop') {
                    // console.log('pinch zoom:' + evt.zoom + ', singleZoom: ' + evt.singleZoom);
                    that.processEvent(evt);
                }
                //evt.zoom代表两个手指缩放的比例(多次缩放的累计值),evt.singleZoom代表单次回调中两个手指缩放的比例
                // console.log('pinch:' + JSON.stringify(evt));
            },
            pressMove: function (evt) {
                //evt.deltaX和evt.deltaY代表在屏幕上移动的距离,evt.target可以用来判断点击的对象
                // console.log(evt.target);
                // console.log(evt.deltaX);
                // console.log(evt.deltaY);
            },
            swipe: function (evt) {
                //在touch结束触发，evt.direction代表滑动的方向 ['Up','Right','Down','Left']
                // console.log('swipe:' + evt.direction);
            },
        });
        global.wxNodes ??= {};
        global.wxNodes.nodeIdStack ??= [];
        global.wxNodes.nodeIdStack.push(that.__wxExparserNodeId__);
        global.wxNodes[global.wxNodes.nodeIdStack[global.wxNodes.nodeIdStack.length - 1]] = that;
        global.wx = that;
        that.clientWidth = that.data.mapWidth;
        that.clientHeight = that.data.mapHeight;

        getScenicArea(that.data.rootScenicId, function(d) { 
            that.scenicArea = d; 
            that.triggerEvent('updateBarTitle', {
                scenicName: that.scenicArea.name
            })  
            that.scenicArea.createMap(that, function() {
                that.scenicArea.initTileLayer(); 
                that.scenicArea.showAreaContour();
                that.scenicArea.initPois(); 

                let _roadMultiArray = [['无'],[]];
                for (let i=0; i<that.scenicArea.road_type_list.length; ++i) {
                  _roadMultiArray[0].push(that.scenicArea.road_type_list[i].name);
                //   if (i == 0) {
                //     for (let m=0; m<that.scenicArea.road_type_list[i].roads.length; ++m) {
                //       _roadMultiArray[1].push(that.scenicArea.road_type_list[i].roads[m].name);
                //     }
                //   }
                }

                that.setData({
                    rootScenicId: that.scenicArea.id,
                    scenicTypeList: that.scenicArea.children_scenic_area_type,
                    roadMultiArray: _roadMultiArray,
                    showRoadControl: that.scenicArea.road_type_list.length > 0,
                    compassRotateAngle: that.scenicArea.compassRotateAngle ?? 0,
                    multimap: that.scenicArea.multimap ?? [],
                    markerBorderColor: that.scenicArea.cma_color,
                })
            }); 
        });
    },
    detached: function () {
        var that = this;
        if (that.audioContext != null) {
            that.audioContext.stop();
            that.audioContext.destroy();
            that.audioContext = null;
        }
        if (that.scenicArea.cron_task_mng != null) {
            that.scenicArea.cron_task_mng.stop();
            that.scenicArea.cron_task_mng = null;
        }
    }
  },
  pageLifetimes: {
    show: function() {
      console.log('show page')
      var that = this;
      if (that.scenicArea != null && that.scenicArea.cron_task_mng != null 
            && !that.scenicArea.cron_task_mng.running) {
          that.scenicArea.cron_task_mng.start();
      }
    },
    hide: function() {
      console.log('hide page')
      var that = this;
      if (that.scenicArea != null && that.scenicArea.cron_task_mng != null
            && that.scenicArea.cron_task_mng.running) {
          that.scenicArea.cron_task_mng.stop();
      }
    },
  }
})
